﻿// 初始化数据加载写在此组件内，并通过 TokenContext reload方法实现全局重载

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.JSInterop;

namespace  BootstrapBlazorApp.Shared.Shared;

/// <summary>
/// 全局初始化组件
/// </summary>
public sealed class GlobalTokenInitialize : ComponentBase, IDisposable
{
    [Inject] AuthenticationStateProvider? StateProvider { get; set; }

    /// <summary>
    /// 当前会话状态
    /// </summary>
    [Parameter]
    public TokenContext? Context { get; set; }

    /// <summary>
    ///
    /// </summary>
    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    private bool IsInitialized { get; set; }

    private DotNetObjectReference<GlobalTokenInitialize>? Interop { get; set; }

    /// <summary>
    /// 组件初始化方法
    /// </summary>
    protected override void OnInitialized()
    {
        if (Context is not null)
        {
            Context.ReloadApplication += ReloadApplication;
        }
    }

    /// <summary>
    /// BuildRenderTree 方法
    /// </summary>
    /// <param name="builder"></param>
    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        if (Context is null)
        {
            return;
        }

        RenderFragment content = _builder =>
        {
            _builder.OpenComponent<GlobalTokenRefresh>(3);
            _builder.CloseComponent();
            if (IsInitialized)
            {
                _builder.AddContent(4, ChildContent);
            }
        };

        builder.OpenComponent<CascadingValue<ITokenContext>>(0);
        builder.AddAttribute(1, nameof(CascadingValue<ITokenContext>.Value), Context);
        builder.AddAttribute(2, nameof(CascadingValue<ITokenContext>.ChildContent), content);
        builder.CloseComponent();
    }

    /// <summary>
    /// OnAfterRenderAsync
    /// </summary>
    /// <param name="firstRender"></param>
    /// <returns></returns>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            Interop = DotNetObjectReference.Create(this);
        }

        //后续需要增加次数限制和异常提示，避免死循环
        //如果IsInitialized是false，则需要重新加载初始数据并强制刷新界面
        if (IsInitialized)
        {
            //await Js.HideGlobalOverlay();
        }
        else
        {
            //await Js.ShowGlobalOverlay();

            IsInitialized = true;

            try
            {
                if (Context is not null)
                {
                    //如果未授权，重新读取一次token
                    if (StateProvider is not null && !Context.IsAuthenticated)
                    {
                        Context.LoadToken(await StateProvider.GetAuthenticationStateAsync());
                    }

                    await LoadInitializationData();
                }
            }
            catch { }

            //if (firstRender)
            //{
            //    await Js.NotifyAppIsReady(Interop, nameof(ReloadApplication));
            //}

            //初始数据重新加载后需要刷新一次
            StateHasChanged();
        }
    }

    /// <summary>
    /// 重载系统
    /// </summary>
    /// <returns></returns>
    [JSInvokable]
    public async void ReloadApplication()
    {
        IsInitialized = false;

        await InvokeAsync(StateHasChanged);
    }

    /// <summary>
    /// 加载初始数据
    /// </summary>
    /// <returns></returns>
    private async Task<bool> LoadInitializationData()
    {
        if (Context is null)
        {
            return false;
        }

        if (Context.IsAuthenticated)
        {
            //if (SysAuthService is not null)
            //{
            //    //重新初始化用户数据
            //    var data = await SysAuthService.GetLoginUserAsync();
            //    Context.SetSession(ClientAppKey.InitedTime, DateTime.Now);
            //    Context.SetSession(ClientAppKey.GlobalApps, data?.Apps);
            //    Context.SetSession(ClientAppKey.CurrentNavs, data?.Navs);
            //    Context.SetSession(ClientAppKey.UserUnlimit, data?.AdminType == 1);
            //    Context.SetSession(ClientAppKey.UserAdminType, data?.AdminType);
            //    Context.SetSession(ClientAppKey.UserPermissions, data?.AllPermissions);
            //}
        }

        return true;
    }

    /// <summary>
    /// 加载初始模块
    /// </summary>
    /// <returns></returns>
    private async Task<bool> LoadInitializationModule()
    {
        //ssr不用预加载模块（也可以预加载）
        if (!OperatingSystem.IsBrowser())
        {
            return true;
        }

        //预加载模块写在这里

        return await Task.FromResult(true);
    }

    public void Dispose()
    {
        if (Context is not null)
        {
            Context.ReloadApplication -= ReloadApplication;
        }
        GC.SuppressFinalize(this);
    }
}
